package com.wondertek.common.log;

import com.wondertek.common.util.base.IpUtils;
import com.wondertek.common.util.security.LoginUser;
import com.wondertek.common.util.security.SecurityUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author xqs
 */
@SuppressWarnings("all")
@Slf4j
@Aspect
@Configuration
@EnableAspectJAutoProxy
public class AutoLogAspect {

    @Resource
    private AutoLogService autoLogService;

    /**
     * 匹配切面
     */
    @Pointcut("@annotation(com.wondertek.common.log.AutoLog)")
    public void logPointCut() {
    }

    /**
     * 执行方法
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        String ip = IpUtils.getIpAddr();
        Object result = null;
        Throwable tr = null;
        try {
            result = point.proceed();
        } catch (Throwable e) {
            result = e.getMessage();
            tr = e;
            throw e;
        } finally {
            try {
                LoginUser loginUser = SecurityUtil.getDefaultLoginUser();
                // 异步记录日志
                autoLogService.asyncPoressLog(point, result, startTime, ip, loginUser, tr);
            } catch (Throwable throwable) {
                log.error("AOP记录日志失败！", throwable);
            }finally {
                SecurityUtil.SecurityContext.remove();
            }
        }
        return result;
    }
}
